<template>
<el-popover ref="top" :placement="placement" trigger="click" :width="width" v-model:visible="visible">
    <template #reference>
        <span ref="reference"><slot name="reference"></slot></span>
    </template>
    <slot></slot>
</el-popover>
</template>

<script lang="ts" setup>
import {ref, withDefaults, Ref, watch } from 'vue'

const visible = ref(false)

interface Props {
    placement?: string, 
    trigger?: string, 
    width?: number|string,
    popup: boolean,
}
const props = withDefaults(
    defineProps<Props>()
    , {
        width: 'auto' ,
        popup:false ,
        trigger: 'click'
    }
)

const emit = defineEmits(["update:popup"])
const reference = ref(null) as unknown as Ref<HTMLElement>
const top = ref(null) as unknown as Ref<HTMLElement>

watch(()=>props.popup, ()=>{
    visible.value = props.popup
})

$(document).click((e)=>{
    if(!visible.value) {
        return
    }
    let parents = $(e.target).parents().toArray()
    if(parents.includes(reference.value) || parents.includes(top.value)) {
        return
    }
    visible.value = false
    emit("update:popup", false)
})

</script>